import { defineStore } from 'pinia';
import { reactive, ref } from 'vue';

export const useContactStore = defineStore('contacts', () => {
  const contacts = ref([]);
  const initContacts = (res) => {
    // 先清空现有数据
    contacts.value = [];
  
    contacts.value = res.map(element => {
      const messages = (element.messages || []).map(msg => {
        let parsedContent = msg.content;
        try {
          const parsed = JSON.parse(msg.content);
          parsedContent = parsed.content || msg.content;
        } catch (e) {
          // 解析失败就用原始字符串
          
        }
  
        return {
          sender: msg.senderId,
          time: msg.timestamp.replace('T', ' '),
          content: parsedContent
        };
      });
  
      return {
        id: element.orderNo,
        name: element.friendId,
        avatar: 'https://picsum.photos/50/50',
        unreadCount: element.unreadCount || 0,
        messages
      };
    });
    console.log("初始化聊天列表成功", contacts.value);
  };
  
  // 添加联系人
  const addContact = (contact) => {
    const exists = contacts.value.find(c => c.id === contact.id);
    if (!exists) {
      contacts.value.push(contact);
    }
  };

  const addMessage = (message)=>{
    contacts.value.find(c=>c.name === message.senderId).messages.push(message);
  }

  const add = (contact)=>{
    contacts.value.push(contact);
  }


  // 删除联系人
  const deleteContact = (contactId) => {
    const index = contacts.value.findIndex(c => c.id === contactId);
    if (index !== -1) {
      contacts.value.splice(index, 1);
    }
  };

  // 设置联系人未读消息数
  const setUnreadCount = (contactId, count) => {
    const contact = contacts.value.find(c => c.name === contactId);
    if (contact) {
      contact.unreadCount = count;
    }
  };

  // 置顶联系人
  const pinContact = (contactId) => {
    const index = contacts.value.findIndex(c => c.id === contactId);
    if (index !== -1) {
      const pinnedContact = contacts.value.splice(index, 1)[0];
      contacts.value.unshift(pinnedContact);
    }
  };

  //

  return {
    contacts,
    addContact,
    deleteContact,
    setUnreadCount,
    pinContact,
    add,
    addMessage,
    initContacts
  };
});
